package dao

import (
	"github.com/PhlexTheCharr/gofurry-cloud-service/apps/openlist/manage/util/models"
	"github.com/PhlexTheCharr/gofurry-cloud-service/common"
	"github.com/PhlexTheCharr/gofurry-cloud-service/common/abstract"
	cm "github.com/PhlexTheCharr/gofurry-cloud-service/common/models"
	"gorm.io/gorm"
)

var newUtilManageDao = new(UtilManageDao)

func init() {
	newUtilManageDao.Init()
}

type UtilManageDao struct{ abstract.Dao }

func GetUtilManageDao() *UtilManageDao { return newUtilManageDao }

// 分页查询
func (dao UtilManageDao) Paginate(req *models.SayingPageQuery) (cm.PageResponse, common.GFError) {
	var total int64 = 0
	var list []models.SayingPageVo
	pageData := cm.PageResponse{}
	db := dao.Gm.Table("ol_saying ols")
	buildGamePageCondition(db, req)
	db.Count(&total).Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize)
	db.Find(&list)
	if err := db.Error; err != nil {
		return pageData, common.NewDaoError(err.Error())
	}
	pageData.Data = list
	pageData.Total = total
	return pageData, nil
}

// 构建查询条件
func buildGamePageCondition(db *gorm.DB, req *models.SayingPageQuery) {
	// 模糊查询
	if req.Author != nil {
		db.Where("ols.author LIKE CONCAT('%', ?::text, '%')", *req.Author)
	}
	if req.Saying != nil {
		db.Where("ols.saying LIKE CONCAT('%', ?::text, '%')", *req.Saying)
	}
}
